<template>
  <div id="popupbody" v-if="dialogVisible">
    <div class="popupbody-box">
      <div class="popupbody-title">
        <span>选择当日餐品</span>
        <span class="el-icon-close" @click="closePOpup"></span>
      </div>
      <div class="popupbody-boxin" style="padding:10px;">
        <div class="hearder-search">
          <div class="breadcrumb-container">
            <el-input v-model="searchForm.name" placeholder="餐品名称" @keyup.enter.native="searchBtn" size="small" class="w-140 mr-10"></el-input>
            <el-select placeholder="餐品类目" v-model="searchForm.cat_id" size="small" class="w-140 mr-10">
              <el-option :label="item.name" :value="item.id" v-for="(item, index) in tableList"
                         :key="index"></el-option>
            </el-select>
            <el-button type="primary" @click="searchBtn(1)" size="small"><i class="el-icon-search"></i>搜索</el-button>
            <el-button size="small" @click="searchBtn(2)"><i class="el-icon-refresh"></i>刷新</el-button>
          </div>
        </div>
        <el-table :data="arryList"
                  height="400"
                  @select-all="selectAll"
                  @select="selectFnBox"
                  :stripe="tableStyle.tableStripe"
                  :border="tableStyle.tableBorder"
                  tooltip-effect="dark"
                  @row-click="rowClick"
                  ref="multipleTable">
          <el-table-column
              type="selection"
              width="50"
              align="center">
          </el-table-column>
          <el-table-column label="头像"align="center">
            <template slot-scope="scope">
              <viewerModle type="1" :imgSrc="scope.row.pic"></viewerModle>
            </template>
          </el-table-column>
          <el-table-column
              prop="name"
              label="菜品名称"
              align="center">
          </el-table-column>
          <el-table-column
              prop="catName"
              label="类目"
              align="center">
          </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :current-page="page.pageindex"
            :total="page.total"
            :page-size="page.pagesize"
            @current-change="handleSizeChange">
        </el-pagination>
      </div>
      <div class="popupbody-footer">
        <el-button size="small" @click="closePOpup">返回</el-button>
        <el-button type="primary" size="small" @click="submitFormAdd()">确认并保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {pagination, tableoption} from '@/utils/util.js'

export default {
  name: 'studentMultiple',
  props: ['visible', 'dynamicTagsArray'],
  data() {
    return {
      dialogVisible: this.visible,
      // 设置table样式
      tableStyle: tableoption,
      // 设置table页面分页所需
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      editForm: {
        p: '',
        name: ''
      },
      arryList: [],
      applyBookBox: {}, // 选中人员信息
      // 搜索
      searchForm: {
        cat_id: '',
        name: ''
      },
      tableList: []
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible) {
        console.log('收到的内容：', this.dynamicTagsArray)
        this.InitFn()
        this.applyBookBox = JSON.parse(JSON.stringify(this.dynamicTagsArray))
        this.cateListFn()
      }else{
        this.page.pageindex = 1
        this.tableList = []
        this.arryList= []
      }
    }
  },
  created() {
  },
  methods: {
    cateListFn () {
      this.$fetch(this.api.cate_list, {
        p: 1
      }).then((response) => {
        if (response.code === 0) {
          for (let i in response.list.data) {
            this.tableList.push(response.list.data[i])
          }
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 初始化
    async InitFn() {
      let n = this;
      this.searchForm.p = this.page.pageindex
      let data = await this.$fetch(this.api.food_list, this.searchForm)
      if(!data.code){
        this.arryList = data.list.data;
        this.page.total = data.list.total;
        n.$nextTick(function () {
          n.checked() // 每次更新了数据，触发这个函数即可。
        })
      }
    },
    // 搜索
    searchFn(option) {
      this.page.pageindex = 1
      this.searchForm = option
      this.InitFn()
    },
    // 设置默认选中
    checked() {
      for (let i = 0; i < this.arryList.length; i++) {
        if (this.applyBookBox[this.arryList[i].id]) {
          this.$refs.multipleTable.toggleRowSelection(this.arryList[i], true)
        } else {
          this.$refs.multipleTable.toggleRowSelection(this.arryList[i], false)
        }
      }
    },
    // 点击全选
    selectAll(val) {
      console.log('全选val:', val)
      // 全选所有跟空值，即使页面已经选择2项
      let applyBookBox = this.applyBookBox
      if (val.length !== 0) {
        // this.handleSelection = val
        for (let i = 0; i < val.length; i++) {
          if (!applyBookBox[val[i].id]) {
            // 不存在图书
            applyBookBox[val[i].id] = val[i]
          }
        }
      } else {
        // 清除所有 arryList
        for (let i = 0; i < this.arryList.length; i++) {
          if (this.applyBookBox[this.arryList[i].id]) {
            // 存在图书删除
            delete applyBookBox[this.arryList[i].id]
          }
        }
      }
      this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox) // 更新视图对象
    },
    selectFnBox(val) {
      // 选择的是当前所有的选中，还需要比对未选中项 applyBookBoxInit
      // arryList
      console.log('单选val:', val)
      let valBox = {}
      if (val.length !== 0) {
        for (let i = 0; i < val.length; i++) {
          valBox[val[i].id] = val[i]
        }
      }
      for(let n in this.arryList){
        if(valBox[this.arryList[n].id]){
          this.applyBookBox[this.arryList[n].id] = JSON.parse(JSON.stringify(this.arryList[n]))
        }else{
          delete this.applyBookBox[this.arryList[n].id]
        }
      }
      console.log('applyBookBox:', this.applyBookBox)
    },
    // 单行选中
    rowClick(row, column, event) {
      if (!this.applyBookBox[row.id]) {
        this.applyBookBox[row.id] = row
      } else {
        delete this.applyBookBox[row.id]
      }
      this.applyBookBoxNumber = Object.keys(this.applyBookBox)
      let that = this
      this.$nextTick(function () {
        that.checked() // 每次更新了数据，触发这个函数即可。
      })
    },
    handleSizeChange(val) {
      this.page.pageindex = val
      this.InitFn()
    },
    submitCheckFn() {
      console.log('applyBookBox:', this.applyBookBox)
      if (JSON.stringify(this.applyBookBox) === '{}') {
        this.$message({
          message: '选择教职工',
          type: 'error'
        })
      } else {
        this.$emit('studentFn', this.applyBookBox)
        this.dialogVisible = false
      }
    },
    // 提交数据
    async submitFormAdd() {
      console.log('applyBookBox:', this.applyBookBox)
      if (JSON.stringify(this.applyBookBox) === '{}') {
        this.$message({
          message: '请填特定的学生',
          type: 'error'
        })
      } else {
        this.$emit('studentFn', this.applyBookBox)
        this.closePOpup()
      }
    },
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false)
    },
    searchBtn(option){
      if(option===2){
        this.searchForm.name = '';
        this.searchForm.cat_id = '';
      }
      this.page.pageindex = 1
      this.InitFn()
    }
  },
  mounted() {
  }
}
</script>
<style scoped>
</style>
